#include "exportprogressmanager.h"
#include "mergedexportmanager.h"
#include "unifiedpagerenderer.h"
#include "statusbarmanager.h"
#include <QDebug>
#include <QApplication>
#include <QFileInfo>
#include <QThread>
#include <QDateTime>
#include <QElapsedTimer>
#include <QDir>
#include <QStandardPaths>

ExportProgressManager::ExportProgressManager(QObject* parent)
    : QObject(parent)
    , m_currentStage(ExportStage::Initializing)
    , m_currentProgress(0)
    , m_isExporting(false)
    , m_isPaused(false)
    , m_isCancelled(false)
    , m_analysisTimer(new QTimer(this))
    , m_renderingPrepTimer(new QTimer(this))
    , m_finalizingTimer(new QTimer(this))
    , m_estimator(new ProgressEstimator())
    , m_actualExporter(nullptr)
    , m_pageRenderer(nullptr)
{
    setupStageNames();

    // 设置定时器
    m_analysisTimer->setSingleShot(false);
    connect(m_analysisTimer, &QTimer::timeout, this, &ExportProgressManager::onAnalysisTimer);

    m_renderingPrepTimer->setSingleShot(true);
    connect(m_renderingPrepTimer, &QTimer::timeout, this, &ExportProgressManager::onRenderingPrepTimer);

    m_finalizingTimer->setSingleShot(true);
    connect(m_finalizingTimer, &QTimer::timeout, this, &ExportProgressManager::onFinalizingTimer);

    // 布局处理完成信号连接
    connect(this, &ExportProgressManager::layoutProcessingCompleted,
            this, &ExportProgressManager::startRenderingPrepStage);
}

ExportProgressManager::~ExportProgressManager()
{
    delete m_estimator;
}

void ExportProgressManager::setupStageNames()
{
    m_stageNames[ExportStage::Initializing] = "初始化";
    m_stageNames[ExportStage::FileAnalysis] = "文件分析";
    m_stageNames[ExportStage::LayoutProcessing] = "布局处理";
    m_stageNames[ExportStage::RenderingPrep] = "渲染准备";
    m_stageNames[ExportStage::PDFGeneration] = "PDF生成";
    m_stageNames[ExportStage::Finalizing] = "完成保存";

    // 设置进度范围
    m_stageRanges[ExportStage::Initializing] = {0, 5};
    m_stageRanges[ExportStage::FileAnalysis] = {5, 10};
    m_stageRanges[ExportStage::LayoutProcessing] = {10, 60};
    m_stageRanges[ExportStage::RenderingPrep] = {60, 75};
    m_stageRanges[ExportStage::PDFGeneration] = {75, 95};
    m_stageRanges[ExportStage::Finalizing] = {95, 100};
}

void ExportProgressManager::startExport(const QList<FileData>& files)
{
    if (files.isEmpty()) {
        emit exportFailed("没有文件需要导出");
        return;
    }

    m_files = files;
    m_isExporting = true;
    m_isPaused = false;
    m_isCancelled = false;
    m_currentStage = ExportStage::Initializing;
    m_currentProgress = 0;

    // 生成输出路径
    m_outputPath = generateOutputPath();

    // 启动时间估算
    m_estimator->startTimer();

    // 立即显示初始化阶段
    emitProgressUpdate("正在准备导出...");

    // 快速进入文件分析阶段
    QTimer::singleShot(50, this, &ExportProgressManager::startFileAnalysisStage);
}

void ExportProgressManager::cancelExport()
{

    m_isCancelled = true;
    m_isExporting = false;

    // 停止所有定时器
    m_analysisTimer->stop();
    m_renderingPrepTimer->stop();
    m_finalizingTimer->stop();

    // 立即发出取消信号
    emit exportCancelled();
}

void ExportProgressManager::pauseExport()
{
    if (m_isExporting && !m_isPaused) {
        m_isPaused = true;
        emitProgressUpdate("导出已暂停");
    }
}

void ExportProgressManager::resumeExport()
{
    if (m_isExporting && m_isPaused) {
        m_isPaused = false;
        emitProgressUpdate("继续导出...");
    }
}

void ExportProgressManager::setExportComponents(MergedExportManager* exporter, UnifiedPageRenderer* renderer)
{
    m_actualExporter = exporter;
    m_pageRenderer = renderer;

    if (m_actualExporter) {
        // 连接实际导出器的信号
        connect(m_actualExporter, &MergedExportManager::exportCompleted,
                this, &ExportProgressManager::onActualExportCompleted);
        connect(m_actualExporter, &MergedExportManager::exportFailed,
                this, &ExportProgressManager::onActualExportFailed);
        connect(m_actualExporter, &MergedExportManager::progressUpdated,
                this, &ExportProgressManager::onActualExportProgress);
    }
}

void ExportProgressManager::updateProgress(int percentage, const QString& message)
{
    // 防抖机制：避免过于频繁的进度更新
    static int lastPercentage = -1;
    static QString lastMessage = "";
    static QElapsedTimer updateTimer;
    static const int MIN_UPDATE_INTERVAL = 100; // 最小更新间隔100ms

    // 检查是否需要更新
    bool shouldUpdate = false;
    if (abs(percentage - lastPercentage) >= 1) {
        shouldUpdate = true;
    }
    if (message != lastMessage) {
        shouldUpdate = true;
    }
    if (!updateTimer.isValid() || updateTimer.elapsed() >= MIN_UPDATE_INTERVAL) {
        shouldUpdate = true;
    }

    if (!shouldUpdate) {
        return; // 跳过此次更新
    }

    m_currentProgress = percentage;
    m_currentMessage = message;
    lastPercentage = percentage;
    lastMessage = message;
    updateTimer.restart();

    ProgressInfo info;
    info.percentage = percentage;
    info.message = message;
    info.stage = m_currentStage;

    emit progressUpdated(info);
}

void ExportProgressManager::setCurrentStage(ExportStage stage)
{
    if (m_currentStage != stage) {
        m_currentStage = stage;
        emit stageChanged(stage, m_stageNames.value(stage));

        // 自动设置进度范围
        auto range = m_stageRanges.value(stage);
        m_currentProgress = range.first;
    }
}

void ExportProgressManager::startFileAnalysisStage()
{
    if (checkCancellation()) return;

    setCurrentStage(ExportStage::FileAnalysis);
    setProgressRange(5, 10);
    emitProgressUpdate("正在分析文件...");

    // 启动文件分析定时器
    m_analysisTimer->start(200); // 每200ms更新一次
}

void ExportProgressManager::onAnalysisTimer()
{
    if (checkCancellation()) {
        m_analysisTimer->stop();
        return;
    }

    static int fileIndex = 0;
    if (fileIndex >= m_files.size()) {
        m_analysisTimer->stop();
        fileIndex = 0;
        startLayoutProcessingStage();
        return;
    }

    // 分析单个文件（模拟）
    const auto& file = m_files[fileIndex];
    int progress = 5 + (fileIndex * 5) / m_files.size();
    QString status = QString("正在分析第 %1/%2 个文件...")
                   .arg(fileIndex + 1).arg(m_files.size());

    emitProgressUpdate(status, file.name);
    updateProgress(progress, status);

    fileIndex++;
}

void ExportProgressManager::startLayoutProcessingStage()
{
    if (checkCancellation()) return;

    setCurrentStage(ExportStage::LayoutProcessing);
    setProgressRange(10, 60);
    emitProgressUpdate("正在处理页面布局...");

    // 异步执行布局处理
    executeLayoutProcessing();
}

void ExportProgressManager::executeLayoutProcessing()
{
    // 使用成员变量存储进度状态
    m_layoutFileIndex = 0;
    m_layoutPageIndex = 0;
    m_layoutTotalOperations = 0;
    m_layoutCompletedOperations = 0;

    // 计算总操作数
    for (const auto& file : m_files) {
        m_layoutTotalOperations += file.pageCount;
    }

    // 使用定时器进行模拟处理
    QTimer* layoutTimer = new QTimer(this);
    connect(layoutTimer, &QTimer::timeout, [this, layoutTimer]() {
        if (checkCancellation() || m_layoutFileIndex >= m_files.size()) {
            layoutTimer->stop();
            layoutTimer->deleteLater();

            // 发出布局处理完成信号
            emit layoutProcessingCompleted();
            return;
        }

        const auto& file = m_files[m_layoutFileIndex];
        m_layoutCompletedOperations++;
        int progress = 10 + (m_layoutCompletedOperations * 50) / m_layoutTotalOperations;

        QString fileName = QFileInfo(file.path).baseName();
        QString status = QString("正在处理: %1 (页面 %2/%3)")
                       .arg(fileName).arg(m_layoutPageIndex + 1).arg(file.pageCount);

        emitProgressUpdate(status, fileName);
        updateProgress(progress, status);

        m_layoutPageIndex++;
        if (m_layoutPageIndex >= file.pageCount) {
            m_layoutPageIndex = 0;
            m_layoutFileIndex++;
        }
    });

    layoutTimer->start(50); // 每50ms处理一次
}

void ExportProgressManager::onLayoutProcessingFinished()
{
    if (checkCancellation()) return;

    emit layoutProcessingCompleted();
}

void ExportProgressManager::startRenderingPrepStage()
{
    if (checkCancellation()) return;

    setCurrentStage(ExportStage::RenderingPrep);
    setProgressRange(60, 75);
    emitProgressUpdate("正在准备渲染参数...");

    m_renderingPrepTimer->start(2000); // 2秒后进入PDF生成阶段
}

void ExportProgressManager::onRenderingPrepTimer()
{
    if (checkCancellation()) return;

    // 更新进度
    updateProgress(65, "正在应用图像增强设置...");

    QTimer::singleShot(500, [this]() {
        if (checkCancellation()) return;
        updateProgress(70, "正在设置页码和水印...");

        QTimer::singleShot(500, [this]() {
            if (checkCancellation()) return;
            updateProgress(75, "渲染准备完成");
            startPDFGenerationStage();
        });
    });
}

void ExportProgressManager::startPDFGenerationStage()
{
    if (checkCancellation()) return;

    setCurrentStage(ExportStage::PDFGeneration);
    setProgressRange(75, 95);
    emitProgressUpdate("正在生成PDF文件...");

    if (!m_actualExporter || !m_pageRenderer) {
        emit exportFailed("导出组件未正确设置");
        return;
    }

    // 转换FileData到UnifiedFileInfo
    QList<UnifiedFileInfo> actualFiles;
    ProcessingSettings settings;

    // 这里需要从StatusBarManager或其他地方获取实际的设置
    // 暂时使用默认设置
    settings.standardDPI = 300;

    for (const auto& fileData : m_files) {
        UnifiedFileInfo info;
        info.filePath = fileData.path;
        info.fileName = fileData.name;
        info.pageCount = fileData.pageCount;
        info.layoutMode = static_cast<LayoutMode>(fileData.layoutMode);
        info.enableEnhancement = fileData.enhancementEnabled;
        actualFiles.append(info);
    }

    // 确保输出目录存在
    QFileInfo outputInfo(m_outputPath);
    QDir outputDir = outputInfo.absoluteDir();
    if (!outputDir.exists()) {
        outputDir.mkpath(".");
    }

    // 启动实际的导出操作
    m_actualExporter->startExport(actualFiles, settings, m_outputPath,
                                MergedExportManager::SinglePDF);

    // 给用户一些即时反馈，然后等待实际导出进度
    updateProgress(80, "正在处理页面布局和生成PDF...");
}

void ExportProgressManager::startFinalizingStage()
{
    if (checkCancellation()) return;

    setCurrentStage(ExportStage::Finalizing);
    setProgressRange(95, 100);
    emitProgressUpdate("正在保存文件...");

    m_finalizingTimer->start(1000); // 1秒后完成
}

void ExportProgressManager::onFinalizingTimer()
{
    if (checkCancellation()) return;

    updateProgress(98, "正在清理临时文件...");

    QTimer::singleShot(300, [this]() {
        if (checkCancellation()) return;

        updateProgress(100, "导出完成！");
        m_isExporting = false;
        emit exportCompleted(m_outputPath);
    });
}

void ExportProgressManager::emitProgressUpdate(const QString& message, const QString& currentFile)
{
    ProgressInfo info;
    info.percentage = m_currentProgress;
    info.message = message;
    info.currentFile = currentFile;
    info.stage = m_currentStage;

    // 添加时间预估
    if (m_estimator && m_currentProgress > 0 && m_currentProgress < 100) {
        auto estimate = m_estimator->getRemainingTime(m_currentProgress);
        info.estimatedTime = QString("预计剩余: %1").arg(estimate.formattedTime);
    }

    emit progressUpdated(info);
}

void ExportProgressManager::setProgressRange(int min, int max)
{
    auto range = m_stageRanges.value(m_currentStage);
    m_currentProgress = min;
}

bool ExportProgressManager::checkCancellation() const
{
    if (m_isCancelled) {
        return true;
    }
    return false;
}

void ExportProgressManager::onActualExportCompleted(const QString& outputPath)
{
    startFinalizingStage();
}

void ExportProgressManager::onActualExportFailed(const QString& error)
{
    m_isExporting = false;
    emit exportFailed(error);
}

void ExportProgressManager::onActualExportProgress(int percentage)
{
    // 将实际导出进度平滑映射到我们的PDF生成阶段范围(75-95)
    // 使用二次函数使进度增长更加平滑
    float normalizedProgress = percentage / 100.0f;
    float smoothProgress = normalizedProgress * normalizedProgress; // 平滑二次曲线
    int mappedProgress = 75 + (int)(smoothProgress * 20); // 将0-100映射到75-95

    updateProgress(mappedProgress, QString("PDF生成进度: %1%").arg(percentage));
}

QString ExportProgressManager::generateOutputPath()
{
    // 生成输出路径的逻辑
    QString timestamp = QDateTime::currentDateTime().toString("MMdd-hhmm");

    // 使用标准的文档位置
    QString documentsPath = QStandardPaths::writableLocation(QStandardPaths::DocumentsLocation);
    QString exportDir = documentsPath + "/PDF导出";

    // 确保导出目录存在
    QDir dir;
    if (!dir.exists(exportDir)) {
        dir.mkpath(exportDir);
    }

    return QString("%1/材料-%2.pdf").arg(exportDir).arg(timestamp);
}